package com.example.myapplication.Fragment;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.myapplication.activity.LoadingActivity;
import com.example.myapplication.R;
import com.example.myapplication.activity.SongDetail1Activity;
import com.example.myapplication.api.MusicApiService;
import com.example.myapplication.entity.HotSongs;
import com.example.myapplication.entity.RecommendSongs;
import com.example.myapplication.entity.Song;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import me.zhengken.lyricview.LyricView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class  SongDetailFragment extends Fragment {
    private View view;
    private ImageButton start;
    private ImageButton skip_pre;
    private ImageButton skip_next;
    private MediaPlayer mediaPlayer;
    private ImageView img_al;
    private TextView song_name;
    private HotSongs hotSongs;
    private View container;
    private TextView singer_name;
    private TextView song_desc;
    private SeekBar seekBar;
    private Timer timer;
    private TextView start_time;
    private TextView finish_time;
    private ObjectAnimator objectAnimator;
    public static final int STATE_PLAYING =1;//正在播放
    public static final int STATE_PAUSE =2;//暂停
    public static final int STATE_STOP =3;//停止
    public int state = STATE_STOP;
    private LyricView lrcView;
    private LrcFragment lrcFragment;
    private ImageButton start_lrc;
    private String mp3Url;
    public static SongDetailFragment fragment;

    public SongDetailFragment() {

    }

    public static SongDetailFragment newInstance(Bundle bundle) {
        if(fragment==null) {
            fragment = new SongDetailFragment();
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_song_detail, container, false);
        lrcFragment = LrcFragment.newInstance(null);
        init();
        loadData(hotSongs.getId());
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        skip_pre = view.findViewById(R.id.skip_pre);
        skip_next = view.findViewById(R.id.skip_next);
        start = view.findViewById(R.id.start);
        start.setOnClickListener(this::onClick);
        skip_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Gson gson = new Gson();
                RecommendSongs.DataBean.DailySongsBean dailySongs = LoadingActivity.recommendSongsList.get((int) (Math.random()*30));
                String json = gson.toJson(dailySongs);
                HotSongs hotSongs = gson.fromJson(json,HotSongs.class);
//

                Intent intent1 = new Intent(getContext(), SongDetail1Activity.class);

                Bundle bundle = new Bundle();
                bundle.putSerializable("song",hotSongs);
                intent1.putExtras(bundle);
                getContext().startActivity(intent1);
                getActivity().finish();
            }
        });

        skip_pre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)  {
                Gson gson = new Gson();
                RecommendSongs.DataBean.DailySongsBean dailySongs = LoadingActivity.recommendSongsList.get((int) (Math.random()*30));
                String json = gson.toJson(dailySongs);
                HotSongs hotSongs = gson.fromJson(json,HotSongs.class);

                Intent intent1 = new Intent(getContext(), SongDetail1Activity.class);

                Bundle bundle = new Bundle();
                bundle.putSerializable("song",hotSongs);
                intent1.putExtras(bundle);
                getContext().startActivity(intent1);
                getActivity().finish();
            }
        });

        mediaPlayer = new MediaPlayer();
        song_name = view.findViewById(R.id.song_name);
        img_al = view.findViewById(R.id.img_al);
        container = view.findViewById(R.id.container);
        singer_name = view.findViewById(R.id.singer_name);
        song_desc  = view.findViewById(R.id.song_desc);
        seekBar = view.findViewById(R.id.seek_bar);
        seekBar.setOnSeekBarChangeListener(new MySeekBar());
        start_time = view.findViewById(R.id.start_time);
        finish_time = view.findViewById(R.id.finish_time);

        //图片旋转
        objectAnimator = ObjectAnimator.ofFloat(img_al, "rotation", 0f, 360f);
        objectAnimator.setDuration(35000);//设定转一圈的时间
        objectAnimator.setInterpolator(new LinearInterpolator());
        objectAnimator.setRepeatCount(ObjectAnimator.INFINITE);//设定无限循环
        objectAnimator.setRepeatMode(ObjectAnimator.RESTART);


        hotSongs = (HotSongs) getArguments().getSerializable("song");
        String alName = hotSongs.getAl().getName();
        String songName = hotSongs.getName();
        String singerName = hotSongs.getAr().get(0).getName();
        if(alName==null){
            alName = "null";
        }
        if(songName==null){
            songName = "null";
        }
        if(singerName==null){
            singerName = "null";
        }
        song_desc.setText(songName+"-"+singerName+"-"+alName);
        song_name.setText(songName);
        singer_name.setText(singerName);
        String url = hotSongs.getAl().getPicUrl();


        start_time.setText("0:0");

        RoundedCorners roundedCorners= new RoundedCorners(30);
        RequestOptions options1= RequestOptions
                .bitmapTransform(roundedCorners)
                .circleCrop();
        Glide.with(this).load(url)
                .centerCrop()
                .error(R.drawable.ic_baseline_refresh_24)
                .placeholder(R.drawable.ic_baseline_refresh_24)
                .apply(options1)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(img_al);
    }

    public void onClick(View v) {
        lrcView = lrcFragment.getLrcView();
        lrcView.setOnPlayerClickListener(new LyricView.OnPlayerClickListener() {
            @Override
            public void onPlayerClicked(long progress, String content) {
                mediaPlayer.seekTo((int) progress);
            }
        });
        start_lrc = lrcFragment.getStart_lrc();
        if(state == STATE_STOP){
            objectAnimator.start();//动画开始
            state = STATE_PLAYING;
        }
        else if(state == STATE_PAUSE){
            objectAnimator.resume();//动画重新开始
            state = STATE_PLAYING;
        }
        if (!mediaPlayer.isPlaying() && mp3Url !=null) {
            mediaPlayer.start();
            start_lrc.setImageResource(R.drawable.ic_baseline_pause_24);
            start.setImageResource(R.drawable.ic_baseline_pause_24);
            //定时器每秒钟更改进度条
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    seekBar.setProgress(mediaPlayer.getCurrentPosition());
                }
            },0,1000);
        }
        else{
            mediaPlayer.pause();
            start_lrc.setImageResource(R.drawable.ic_baseline_play_arrow_24);
            start.setImageResource(R.drawable.ic_baseline_play_arrow_24);
            timer.cancel();
            if(state == STATE_PLAYING){
                objectAnimator.pause();//动画暂停
                state = STATE_PAUSE;
            }
        }
    }

    public class MySeekBar implements SeekBar.OnSeekBarChangeListener {

        //进度条改变时
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            int s = mediaPlayer.getCurrentPosition() / 1000;
            String total = s / 60 + ":" + s % 60;
            start_time.setText(total);

            if(lrcView!=null) {
                lrcView.setCurrentTimeMillis(mediaPlayer.getCurrentPosition());
            }
            //处理音乐播放结束时，
            if(progress>=seekBar.getMax()-1 ){
                timer.cancel();
                objectAnimator.pause();//动画暂停
                state = STATE_PAUSE;
                start.setImageResource(R.drawable.ic_baseline_play_arrow_24);
                start_lrc.setImageResource(R.drawable.ic_baseline_play_arrow_24);
                seekBar.setProgress(0);
                start_time.setText("0:0");
            }
        }

        //接触进度条时
        public void onStartTrackingTouch(SeekBar seekBar) {
        }
        /*滑动结束后，重新设置值*/
        public void onStopTrackingTouch(SeekBar seekBar) {
            mediaPlayer.seekTo(seekBar.getProgress());
            int s = mediaPlayer.getCurrentPosition() / 1000;
            String total = s / 60 + ":" + s % 60;
            start_time.setText(total);
        }
    }

    private void initMediaPlayer(String mp3url) {
        try {
            if(mp3url!=null) {
                mediaPlayer.setDataSource(mp3url);
                mediaPlayer.prepare();
                seekBar.setMax(mediaPlayer.getDuration());
                int s = mediaPlayer.getDuration() / 1000;
                String total = s / 60 + ":" + s % 60;
                finish_time.setText(total);
            }
            else{
                Toast.makeText(getContext(), "暂时没有版权，听听别的歌吧", Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        objectAnimator.end();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
        }
        if(timer!=null)
            timer.cancel();
    }

    private void loadData(int id){
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://autumnfish.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        MusicApiService service =  retrofit.create(MusicApiService.class);

        Call<Song> call = service.getSong(LoadingActivity.cookie,id);
        call.enqueue(new Callback<Song>() {
            @Override
            public void onResponse(Call<Song> call, Response<Song> response) {
                Song baseResponse = response.body();
                 mp3Url =  baseResponse.getData().get(0).getUrl();
                initMediaPlayer(mp3Url);
            }
            @Override
            public void onFailure(Call<Song> call, Throwable t) {

                t.printStackTrace();
            }

        });
    }
}
